<template>
    <canvas id="canvas"></canvas>

    <img id="img" /> 
</template>

<script setup>
import { onMounted } from 'vue'


let canvas, ctx, startPoint, endPoint;

onMounted(() => {
    canvas = document.getElementById('canvas'),
        ctx = canvas.getContext('2d');
})

function drawCanvas() {
    // ctx.clearRect(0, 0, canvas.width, canvas.height);
    console.log('drawCanvas....>');
    ctx.beginPath();
    ctx.rect(startPoint.x, startPoint.y, endPoint.x - startPoint.x, endPoint.y - startPoint.y);
    ctx.fillStyle = 'red';
    ctx.strokeStyle = 'blue';
    ctx.stroke();

   let imageData=  ctx.getImageData(startPoint.x, startPoint.y, endPoint.x - startPoint.x, endPoint.y - startPoint.y)


   console.log('imageData......>',imageData)

   let url = canvas.toDataURL();

   var img = document.getElementById('img')
   img.src = url;

   ctx.globalCompositeOperation  = 'source-in'

   ctx.drawImage(img, endPoint.x - startPoint.x, endPoint.y - startPoint.y)

}


window.addEventListener('mousedown', function (event) {
    console.log('mousedown....>', event);
    startPoint = {
        x: event.offsetX,
        y: event.offsetY
    }
})

window.addEventListener('mouseup', function (event) {
    console.log('mouseup....>', event);
    endPoint = {
        x: event.offsetX,
        y: event.offsetY
    }

    drawCanvas();
}) 
</script>

<style scope lang="scss">
#canvas {
    border: 1px solid red;
}

img {
    border:1px solid pink
}
</style>